package org.itboys.core.service.mysql.front;

import com.alibaba.fastjson.JSONObject;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.order.SundayOrderSceneMapper;
import org.itboys.core.dto.count.SundayCountDto;
import org.itboys.core.dto.count.SundayCountSceneDto;
import org.itboys.core.dto.goods.SundayGoodsSizeDto;
import org.itboys.core.dto.order.SundayOrderDto;
import org.itboys.core.dto.scene.SundaySceneDto;
import org.itboys.core.entity.mongo.*;
import org.itboys.core.entity.mysql.SundayOrder;
import org.itboys.core.entity.mysql.SundayOrderScene;
import org.itboys.core.service.mongo.front.*;
import org.itboys.core.service.mongo.web.SundaySceneService;
import org.itboys.core.util.JNBYRequestUtil;
import org.itboys.core.util.NumberUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作者：zzq
 * 时间：2018/10/23
 * 描述：订单
 */
@Service
public class SundayFrontOrderService extends BaseMySqlService<SundayOrder> {
    @Autowired
    private SundayFrontAddressService addressService;
    @Autowired
    private SundayFrontCountService countService;
    @Autowired
    private SundayFrontCartService cartService;
    @Autowired
    private SundaySceneService sceneService;
    @Autowired
    private SundayOrderSceneMapper orderSceneMapper;
    @Autowired
    private SundayFrontMemberService memberService;
    @Autowired
    private SundayFrontGiftService giftService;
    @Autowired
    private SundayFrontCartGoodsSizeService sizeService;

    @Transactional
    public Map<String, Object> createOrder(Long memberId, List<Long> cartIds, String remark, Long addressId) throws IOException {
        //检测库存
        checkStore(cartIds);
        Map<String, Object> result = new HashMap<>(0);
        String orderIds = "";//需要支付的订单
        SundayAddress address = new SundayAddress();//收货地址
        //获取购物车数据
        SundayCountDto countDto = countService.countCart(memberId, cartIds, null, SundayCommonConstants.NO);
        if (countDto.getCartType() != SundayCommonConstants.cart_type_send) {
            if (!LongUtil.isNotZreo(addressId)) {
                throw new ErrorException("请选择一个收货地址");
            } else {
                address = addressService.getById(addressId);
            }
        }

        /**
         * 准备订单数据
         */
        SundayOrder order = new SundayOrder();
        order.setOrderNo(NumberUtil.generateNumber("HOME"));
        order.setRemark(remark);
        if (countDto.getCartType() != SundayCommonConstants.cart_type_send) {
            order.setProvinceId(address.getProvinceId());
            order.setProvinceName(address.getProvinceName());
            order.setCityId(address.getCityId());
            order.setCityName(address.getCityName());
            order.setDistrictId(address.getDistrictId());
            order.setDistrictName(address.getDistrictName());
            order.setReceiveMobile(address.getReceiveMobile());
            order.setReceiveName(address.getReceiveName());
            order.setReceiveAddress(address.getReceiveAddress());
        }
        SundayMember member = memberService.getById(memberId);
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_DFK);
        order.setIsCreateOrder(SundayCommonConstants.NO);
        order.setMemberId(memberId);
        order.setOwnerId(memberId);
        order.setUserId(member.getCUserId());
        order.setCartType(countDto.getCartType());
        order.setDescription("由HOME小程序传入网店订单生成！");
        order.setPayAmount(new BigDecimal(countDto.getPayAmount()));
        order.setTotalAmount(new BigDecimal(countDto.getTotalAmount()));
        //保存订单
        super.insert(order);

        for (SundayCountSceneDto sceneDto : countDto.getScenes()) {

            SundayOrderScene orderScene =
                    new SundayOrderScene(order.getId(), sceneDto.getId(), sceneDto.getName(), sceneDto.getViceName(),
                            sceneDto.getImage(), sceneDto.getDesc(), sceneDto.getPrice(), sceneDto.getNum());
            orderSceneMapper.insert(orderScene);
        }
        //购物车生成订单  修改购物车订单Id
        cartService.cartToOrder(countDto.getCarts(), order.getId());

        orderIds = order.getId().toString();
        result.put("payAmount", order.getPayAmount().toString());
        result.put("orderIds", orderIds);
        result.put("cartType", order.getCartType());
        result.put("msg", "");

        return result;
    }

    /**
     * 分页获取订单
     *
     * @param request
     * @param memberId
     * @param orderStatus
     * @return
     */
    public List<SundayOrderDto> selectOrder(HttpServletRequest request, Long memberId, Integer orderStatus) throws IOException {
        //1，全部订单
        //1.1   获取全部订单
        //1.2   查询待配送的江南布衣订单
        //1.3   匹配订单更改状态
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "orderNo", "createTime_start", "createTime_end");
        param.put("memberId", memberId);
        if (orderStatus != 0) {
            if (orderStatus == SundayCommonConstants.ORDER_STATUS_PSZ) {
                param.put("orderStatus", SundayCommonConstants.ORDER_STATUS_DPS);
            } else {
                param.put("orderStatus", orderStatus);
            }
        }
        List<SundayOrder> orders = super.select(param);
        List<SundayOrder> _orders = new ArrayList<>();
        List<String> orderNos = new ArrayList<>();
        if (ListUtil.isNotNull(orders)) {
            for (SundayOrder order : orders) {
                orderNos.add(order.getOrderNo());
            }
            JSONObject paramJson = new JSONObject();
            paramJson.put("orderNos", orderNos);
            paramJson.put("pageNo", 1);
            paramJson.put("pageSize", 20);
            JSONObject requestResult = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_select_url);
            logger.info("江南布衣订单列表请求结果" + requestResult.toJSONString());
            List<JSONObject> jsonObjects = (List<JSONObject>) requestResult.get("data");
            if (ListUtil.isNotNull(jsonObjects)) {
                for (SundayOrder order : orders) {
                    for (JSONObject object : jsonObjects) {
                        Integer _orderStatus = (Integer) object.get("orderStatus");
                        if (object.get("orderNo").equals(order.getOrderNo()) ) {
                            if (order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_DPS&&_orderStatus == 2) {
                                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
                                break;
                            }
                            if(order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_TKZ&&_orderStatus == 4){
                                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YTK);
                                break;
                            }
                            if(order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_THZ&&_orderStatus == 4){
                                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YTH);
                                break;
                            }

                        }
                    }
                    if (order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_PSZ) {
                        _orders.add(order);
                    }
                }
            }
        }
        if (orderStatus == SundayCommonConstants.ORDER_STATUS_PSZ) {
            return packageMultiDto(_orders);
        }
        return packageMultiDto(orders);
    }

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return
     */
    public SundayOrderDto findOne(Long orderId) throws IOException {
        SundayOrderDto dto = packageSingleDto(super.find(orderId), null);
        JSONObject paramJson = new JSONObject();
        paramJson.put("orderNo", dto.getOrderNo());
        JSONObject object = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_find_url);
        JSONObject data = (JSONObject) object.get("data");
        if(data!=null){
            Integer orderStatus = (Integer) data.get("orderStatus");
            if (orderStatus == 2) {
                dto.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
                dto.setSendCode((String) object.get("fastno"));
            }
            if (dto.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_TKZ&&orderStatus == 4) {
                dto.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YTK);
            }
            if (dto.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_THZ&&orderStatus == 4) {
                dto.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YTH);
            }
        }
        return dto;
    }

    /**
     * 订单收货
     *
     * @param orderId
     */
    @Transactional
    public void receiveOrder(Long orderId) throws IOException {
        SundayOrder order = super.find(orderId);
        //查询江南布衣订单   匹配最新状态
        JSONObject paramJson = new JSONObject();
        paramJson.put("orderNo", order.getOrderNo());
        JSONObject object = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_find_url);
        JSONObject data = (JSONObject) object.get("data");
        Integer orderStatus = (Integer) data.get("orderStatus");
        if (orderStatus == 2) {
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
        }
        if (order.getOrderStatus() != SundayCommonConstants.ORDER_STATUS_PSZ) {
            throw new ErrorException(ExceptionEnum.ORDER_STATUS_EXCEPTION.getValue());
        }
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YSH);
        super.update(order);
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Transactional
    public void cancelOrder(Long orderId) {
        SundayOrder order = super.find(orderId);
        if (order.getOrderStatus() != SundayCommonConstants.ORDER_STATUS_DFK) {
            throw new ErrorException(ExceptionEnum.ORDER_STATUS_EXCEPTION.getValue());
        }
     /*   if(order.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_DPS){
            JSONObject paramJson = new JSONObject();
            paramJson.put("sourceCode", order.getOrderNo());
            JSONObject requestResult =JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_cancel_url);
            logger.info("江南布衣取消订单请求结果"+requestResult.toJSONString());
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YQX);
            super.update(order);
        }*/
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YQX);
        super.update(order);
    }

    /**
     * 转发页面领取礼物
     *
     * @param orderId
     * @param receiveId
     */
    @Transactional
    public Long receiveGift(Long orderId, Long receiveId) {
        SundayOrder order = super.find(orderId);
        Map<String, Object> param = new HashMap<String, Object>();
        if (order.getOwnerId().longValue() == receiveId.longValue()) {
            throw new ErrorException(ExceptionEnum.ORDER_OWNER_EXCEPTION.getValue());
        }
        //如果订单类型不为送礼物
        if (order.getCartType() != 3) {
            throw new ErrorException(ExceptionEnum.ORDER_TYPE_EXCEPTION.getValue());
        }
        //如果已领取  则返回礼物id
        if (order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_YSC) {
            param.clear();
            param.put("receiveId", receiveId);
            param.put("orderId", order.getId());
            param.put("status", SundayCommonConstants.NO);
            param.put("isDeleted", SundayCommonConstants.NO);
            List<SundayGift> oldGifts = giftService.list(param);
            if (ListUtil.isNotNull(oldGifts)) {
                return oldGifts.get(0).getId();
            }
        }
        if (order.getOrderStatus() != SundayCommonConstants.ORDER_STATUS_DPS) {
            throw new ErrorException(ExceptionEnum.ORDER_STATUS_EXCEPTION.getValue());
        }
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YSC);
        order.setMemberId(receiveId);
        SundayOrderDto orderDto = packageSingleDto(order, null);
        super.update(order);
        //判断该订单是否生成了礼物
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("orderId", order.getId());
        List<SundayGift> gifts = giftService.list(param);
        if (ListUtil.isNull(gifts)) {
            //能送出的订单   肯定只有一个场景  所有取第一个
            SundayOrderScene orderScene = orderDto.getScenes().get(0);
            //生成礼物
            SundayGift gift = new SundayGift(order.getOwnerId(), receiveId, orderId, orderScene.getSceneId(),
                    orderScene.getName(), orderScene.getViceName(), orderScene.getImage(), SundayCommonConstants.NO);
            giftService.save(gift);
            return gift.getId();
        }
        return null;

    }

    /**
     * 拆开礼物   同时向江南布衣发起创建订单
     *
     * @param giftId
     * @param receiveName
     * @param receiveMobile
     * @param provinceId
     * @param provinceName
     * @param cityId
     * @param cityName
     * @param districtId
     * @param districtName
     * @param receiveAddress
     */
    @Transactional
    public void openGift(Long giftId, String receiveName, String receiveMobile, Long provinceId, String provinceName,
                         Long cityId, String cityName, Long districtId, String districtName, String receiveAddress) throws IOException {
        SundayGift gift = giftService.getById(giftId);
        SundayOrder order = super.find(gift.getOrderId());

        //如果订单类型不为送礼物
        if (order.getCartType() != 3) {
            throw new ErrorException(ExceptionEnum.ORDER_TYPE_EXCEPTION.getValue());
        }
        //状态判断
        if (order.getOrderStatus() != SundayCommonConstants.ORDER_STATUS_YSC) {
            throw new ErrorException(ExceptionEnum.ORDER_STATUS_EXCEPTION.getValue());
        }
        SundayMember member = memberService.getById(order.getMemberId());
        //如果用户未登陆
        if (member.getIsLogin() != SundayCommonConstants.YES) {
            throw new ErrorException(ExceptionEnum.MEMBER_NO_LONGIN_EXCEPTION.getValue());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("status", SundayCommonConstants.YES);
        param.put("orderId", order.getId());
        List<SundayCart> carts = cartService.list(param);
        List<Long> cartIds = carts.stream().map(e -> e.getId()).collect(Collectors.toList());
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("cartId in", cartIds);
        List<SundayCartGoodsSize> sizes = sizeService.list(param);
        //是否创建了江南布衣订单
        Integer isCreateOrder=0;
        String createOrderMsg = "";
        if (ListUtil.isNotNull(sizes)) {
            JSONObject paramJson = new JSONObject();
            paramJson.put("c_vip_id", member.getCUserId());
            paramJson.put("sourceCode", order.getOrderNo());
            paramJson.put("description", order.getDescription());
            paramJson.put("receiver_name", receiveName);
            paramJson.put("c_province_id", String.valueOf(provinceId));
            paramJson.put("c_city_id", String.valueOf(cityId));
            paramJson.put("c_district_id", String.valueOf(districtId));
            paramJson.put("receiver_address", receiveAddress);
            paramJson.put("receiver_mobile", receiveMobile);
            paramJson.put("source", "MART");
            paramJson.put("outcode", "104");
            List<JSONObject> productItem = new ArrayList<>();
            for (SundayCartGoodsSize size : sizes) {
                JSONObject codeSize = new JSONObject();
                codeSize.put("id", size.getGoodsId());
                codeSize.put("codeId", size.getCodeId());
                codeSize.put("qty", String.valueOf(size.getNum()));
                codeSize.put("priceactual", String.valueOf(size.getPrice()));
                productItem.add(codeSize);
            }
            paramJson.put("productItem", productItem);
            List<JSONObject> payitem = new ArrayList<>();
            JSONObject wxPay = new JSONObject();
            wxPay.put("c_payway_id", "62");
            wxPay.put("payamount", String.valueOf(order.getPayAmount()));
            payitem.add(wxPay);
            paramJson.put("payitem", payitem);
            logger.info("江南布衣礼物创建订单参数 = {}", paramJson.toJSONString());
            JSONObject requestResult = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_add_url);
            logger.info("江南布衣礼物创建订单结果" + requestResult.toJSONString());
            if (requestResult.get("code").equals("0000")) {
                JSONObject data= (JSONObject) requestResult.get("data");
                Integer ret=data.getIntValue("ret");
                createOrderMsg=data.getString("msg");
                if(ret==1){
                    isCreateOrder=1;
                }
            }else {
                logger.info(ExceptionEnum.JNBY_CREATE_ORDER_EXCEPTION.getValue());
                //throw new ErrorException(ExceptionEnum.JNBY_CREATE_ORDER_EXCEPTION.getValue());
            }
        }
        order.setProvinceId(provinceId);
        order.setProvinceName(provinceName);
        order.setCityId(cityId);
        order.setCityName(cityName);
        order.setDistrictId(districtId);
        order.setDistrictName(districtName);
        order.setReceiveMobile(receiveMobile);
        order.setReceiveName(receiveName);
        order.setReceiveAddress(receiveAddress);
        order.setUserId(member.getCUserId());
        order.setIsCreateOrder(isCreateOrder);
        order.setCreateOrderMsg(createOrderMsg);
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YLQ);
        super.update(order);
        gift.setStatus(SundayCommonConstants.YES);
        giftService.updateExceptEmpty(giftId, gift);
    }

    /**
     * 江南布衣申请退款
     * @param orderId
     * @throws IOException
     */
    public void backOrder(Long orderId) throws IOException {
        SundayOrder order = super.find(orderId);
        //查询江南布衣订单   匹配最新状态
        JSONObject paramJson = new JSONObject();
        paramJson.put("orderNo", order.getOrderNo());
        JSONObject object = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_find_url);
        JSONObject data = (JSONObject) object.get("data");
        Integer orderStatus = (Integer) data.get("orderStatus");
        Long jnbyOrderId=data.getLong("orderId");
        if (orderStatus == 2) {
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
        }
        if (order.getOrderStatus() != SundayCommonConstants.ORDER_STATUS_DPS) {
            throw new ErrorException(ExceptionEnum.ORDER_STATUS_EXCEPTION.getValue());
        }
        JSONObject backParamJson = new JSONObject();
        backParamJson.put("sourceCode", order.getOrderNo());
        backParamJson.put("aPPID", "wx9a6eef4114ce9800");
        backParamJson.put("orderId", jnbyOrderId);
        backParamJson.put("refundje", String.valueOf(order.getPayAmount()));
        backParamJson.put("yje", String.valueOf(order.getPayAmount()));
        logger.info("江南布衣退款参数 = {}", backParamJson.toJSONString());
        JSONObject backObject = JNBYRequestUtil.request(backParamJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_cancel_url);
        logger.info("江南布衣退款结果 = {}", backObject.toJSONString());
        JSONObject backData = (JSONObject) backObject.get("data");
        Integer ret = (Integer) backData.get("ret");
        if(ret==1){
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_TKZ);
            super.update(order);
        }else {
            throw new ErrorException(ExceptionEnum.ORDER_BACK_EXCEPTION.getValue());
        }
    }

    /**
     * 退货
     * @param orderId
     */
    public void returnOrder(Long orderId) throws IOException {
        SundayOrder order = super.find(orderId);
        //查询江南布衣订单   匹配最新状态
        JSONObject paramJson = new JSONObject();
        paramJson.put("orderNo", order.getOrderNo());
        JSONObject object = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_find_url);
        JSONObject data = (JSONObject) object.get("data");
        Integer orderStatus = (Integer) data.get("orderStatus");
        if (orderStatus == 2) {
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
        }
        if (order.getOrderStatus() != SundayCommonConstants.ORDER_STATUS_PSZ) {
            throw new ErrorException(ExceptionEnum.ORDER_STATUS_EXCEPTION.getValue());
        }
        Map<String,Object> param=new HashMap<String,Object>();
        JSONObject returnParamJson = new JSONObject();
        SundayMember member = memberService.getById(order.getMemberId());
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("status", SundayCommonConstants.YES);
        param.put("orderId", order.getId());
        List<SundayCart> carts = cartService.list(param);
        List<Long> cartIds = carts.stream().map(e -> e.getId()).collect(Collectors.toList());
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("cartId in", cartIds);
        List<SundayCartGoodsSize> sizes = sizeService.list(param);
        if(ListUtil.isNotNull(sizes)){
            List<JSONObject> productItem=new ArrayList<>();
            Integer tot_qty=0;
            for (SundayCartGoodsSize size : sizes) {
                JSONObject codeSize=new JSONObject();
                codeSize.put("id", size.getGoodsId());
                codeSize.put("codeId", size.getCodeId());
                codeSize.put("qty", String.valueOf(size.getNum()));
                codeSize.put("actual", String.valueOf(size.getPrice()));
                codeSize.put("priceactual", String.valueOf(size.getPrice()));
                productItem.add(codeSize);
                tot_qty+=size.getNum();
            }
            returnParamJson.put("c_vip_id", member.getCUserId());
            returnParamJson.put("sourceCode", order.getOrderNo());
            returnParamJson.put("tot_qty", String.valueOf(tot_qty));
            returnParamJson.put("tot_amt_actual", String.valueOf(order.getPayAmount()));
            returnParamJson.put("productItem", productItem);
            List<JSONObject> payitem=new ArrayList<>();
            JSONObject wxPay=new JSONObject();
            wxPay.put("c_payway_id", "62");
            wxPay.put("payamount", String.valueOf(order.getPayAmount()));
            payitem.add(wxPay);
            returnParamJson.put("payitem", payitem);
            logger.info("江南布衣退货参数 = {}", returnParamJson.toJSONString());
            JSONObject backObject = JNBYRequestUtil.request(returnParamJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_return_url);
            logger.info("江南布衣退货结果 = {}", backObject.toJSONString());
            JSONObject backData = (JSONObject) backObject.get("data");
            Integer ret = (Integer) backData.get("ret");
            if(ret==1){
                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_THZ);
                super.update(order);
            }else {
                throw new ErrorException(ExceptionEnum.ORDER_RETURN_EXCEPTION.getValue());
            }
        }
    }

    /**
     * 检测库存
     * @param cartIds
     * @throws IOException
     */
    public void checkStore(List<Long> cartIds) throws IOException {
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("cartId in", cartIds);
        List<SundayCartGoodsSize> sizes = sizeService.list(param);
        JSONObject paramJson = new JSONObject();
        List<String> codeList = new ArrayList<>();
        for (SundayCartGoodsSize size :sizes) {
            codeList.add(size.getGoodsCode());
        }
        paramJson.put("ids", codeList);
        JSONObject jsonResult = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.goods_store_url);
        List<JSONObject> responseData = (List<JSONObject>) jsonResult.get("data");
        if (ListUtil.isNotNull(responseData)) {
            for (SundayCartGoodsSize size :sizes) {
                for (JSONObject object : responseData) {
                    String objectCode=object.getString("code");
                    Integer objectKcsl=object.getIntValue("kcsl");
                    if(size.getGoodsCode().equals(objectCode)){
                        if(objectKcsl<size.getNum()){
                            throw new ErrorException(ExceptionEnum.GOODS_STORE_EXCEPTION.getValue());
                        }else {
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 组装多个
     *
     * @param orders
     * @return
     */
    public List<SundayOrderDto> packageMultiDto(List<SundayOrder> orders) {
        List<SundayOrderDto> dtos = new ArrayList<>();
        List<Long> orderIds = new ArrayList<>();
        for (SundayOrder order : orders) {
            orderIds.add(order.getId());
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("orderIds", orderIds);
        List<SundayOrderScene> orderScenes = orderSceneMapper.select(param);
        for (SundayOrder order : orders) {
            List<SundayOrderScene> ps = new ArrayList<SundayOrderScene>();
            for (SundayOrderScene orderScene : orderScenes) {
                if (orderScene.getOrderId().longValue() == order.getId()) {
                    ps.add(orderScene);
                }
            }
            dtos.add(packageSingleDto(order, ps));
        }
        return dtos;
    }

    /**
     * 组装DTO
     *
     * @param order
     * @return
     */
    public SundayOrderDto packageSingleDto(SundayOrder order, List<SundayOrderScene> scenes) {
        SundayOrderDto dto = new SundayOrderDto();
        if (ListUtil.isNull(scenes)) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderId", order.getId());
            scenes = new ArrayList<SundayOrderScene>();
            for (SundayOrderScene orderScene : orderSceneMapper.select(param)) {
                if (orderScene.getOrderId().longValue() == order.getId()) {
                    scenes.add(orderScene);
                }
            }
        }
        BeanUtils.copyProperties(order, dto);
        SundayMember ownerMember = memberService.getById(order.getOwnerId());
        dto.setOwnerName(ownerMember.getNickName());
        dto.setScenes(scenes);
        return dto;

    }


}

